package cn.car.interceptor;

import cn.car.service.config.SystemConfig;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTValidator;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.nio.charset.StandardCharsets;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Resource
    private SystemConfig systemConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 获取请求头中的Token
        String token = request.getHeader("Authorization");

        // 2. 检查Token是否存在
        if (token == null || token.trim().isEmpty()) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"message\":\"未提供Token，请先登录\"}");
            return false;
        }

        // 3. 移除可能存在的Bearer前缀（如果前端传递格式为Bearer token）
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }

        try {
            // 4. 创建签名器（需与生成Token时使用的算法一致）
            JWTSigner signer = JWTSignerUtil.hs256(systemConfig.getJwtSecretKey().get().getBytes(StandardCharsets.UTF_8));

            // 5. 验证Token签名和过期时间
            JWTValidator validator = JWTValidator.of(token);
            validator.validateAlgorithm(signer); // 验证签名
            validator.validateDate(); // 验证过期时间

            // 6. 验证通过，将Token中的用户信息存入请求属性，供后续控制器使用
            JWT jwt = JWT.of(token);
            request.setAttribute("userId", jwt.getPayload("userId"));

            return true;
        } catch (Exception e) {
            // 7. 验证失败（签名错误、已过期等）
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"message\":\"Token无效或已过期：" + e.getMessage() + "\"}");
            return false;
        }
    }
}
